/*
This file is part of Jumpers.

Jumpers is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Jumpers is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Jumpers.  If not, see <http://www.gnu.org/licenses/>.
*/
package org.chaoticengine.cgll.entity.component.render;

//~--- non-JDK imports --------------------------------------------------------

import org.chaoticengine.cgll.entity.component.RenderComponent;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.state.StateBasedGame;
import org.simpleframework.xml.Element;

/**
 * Component for rendering game entities by using a image representation. The
 * bounding rectangle for the entity is set as the size of the image.
 *
 * @author Matt v.d. Westhuizen
 */
public class ImageRenderComponent extends RenderComponent {
    private Image img = null;

    public ImageRenderComponent() {
        super();
    }

    @Element(name="image", required=true)
    public String getImage() {
        if (img != null) {
            return(img.getResourceReference());
        } else {
            return("");
        }
    }

    @Element(name="image", required=true)
    public void setImage(String filename) {
        try {
            this.img = new Image(filename);
        } catch (SlickException sEx) {
            sEx.printStackTrace();
            System.out.println("Error: Failed to load image '" + filename + "'.");
        }
    }

    @Override
    public void onSetOwner() {
        Vector2f pos = owner.getPosition();
        owner.setBoundingRectangle(new Rectangle(pos.getX(), pos.getY(), img.getWidth(), img.getHeight()));
    }

    @Override
    public void render(GameContainer gc, StateBasedGame sb, Graphics gr) {
        Vector2f pos = new Vector2f(this.owner.getPosition());

        pos.add(this.owner.getTranslation());

        float rot = img.getRotation();

        img.setRotation(this.owner.getRotation());
        gr.drawImage(img, pos.x, pos.y);
        img.setRotation(rot);
    }
}
